Multiple Charts Example
This example demonstrates how to combine multiple chart types in a single chart context, dynamically display annotations based on user interaction, and customize appearance and interactivity using chart overlays.
Example Code
Overview
The example uses the following components together:
LineChart: Plots discrete points and connects them with curved lines.AreaChart: Fills the area under a line graph, visually indicating magnitude.RuleLineForLabelChart: Draws a reference line at the selected label and overlays a custom annotation.chartXSelection: Enables user interaction by tracking X-axis selection.
Data Format
The dataset used represents yearly sales performance:
Each entry includes:
sales: Numeric value to be plottedyear: Used as the label on the X-axisgrowth: Additional metric (not directly visualized here)
Key Features
Chart Selection
- Enables users to tap or drag on the chart to select a point based on its label (
year). - Triggers the
setChartSelectioncallback to update the selected year.
LineChart
- Plots sales values with labeled X-axis.
- Uses
"catmullRom"for smooth curves between points. - Displays circular symbols for each point.
AreaChart
- Overlays a filled area beneath the line, enhancing visual weight.
- Uses a two-stop gradient from solid to transparent orange.
RuleLineForLabelChart (Dynamic Annotation)
- Shows a vertical gray reference line at the selected year.
- Displays a floating tooltip with the
salesvalue in a styled background. - Uses
ZStackandRoundedRectangleto build a custom annotation view.
User Interaction Flow
- The user touches the chart.
- The closest label (
year) is selected and passed tochartSelection. selectedItemis computed usinguseMemo.- A rule line is rendered at the selected label.
- A floating annotation displays detailed data (e.g.,
Sales: 2500).
Conclusion
This example demonstrates how to:
- Combine multiple charts (
LineChart,AreaChart,RuleLineForLabelChart) within a single<Chart>container. - Use
chartXSelectionto enable touch-based exploration. - Render contextual annotations that enhance data storytelling.
- Apply modern styling using gradient fills, translucent overlays, and SwiftUI-inspired layout components.
This pattern is ideal for dashboards and interactive reports where data insight and responsiveness are key.
